/**
 * Created by zhong on 2018/1/24.
 */
import express from "express"
import mongoose from "mongoose"
import {tools} from "../../mixin/tools"
import Users from "../models/users.js"
import jwt from 'jwt-simple'
import moment from'moment'
let jwtSecret = require('../../util/api.config').jwtSecret

const router = express.Router();
mongoose.Promise = global.Promise

router.post('/register',function (req,res) {
  let userInfo = {
    phone:req.body.phone,
    pwd:req.body.pwd,
  }
  if(!tools.check(0,userInfo.phone)){
    res.json({ success:false,code:404,message: '请输入手机号' })
    return
  }
  if(!tools.check(0,userInfo.pwd)){
    res.json({ success:false,code:404,message: '请输入密码' })
    return
  }
  Users.findOne({phone:userInfo.phone},function (err,doc) {
    if(err) return next(err)
    if(doc){
      res.json({ success:false,code:405,message: '用户已存在，请重新输入' })
    }else{
      userInfo.pwd = require('crypto').createHash('md5').update(userInfo.pwd + userInfo.phone).digest('base64');
      let user = new Users(userInfo)
      user.save(userInfo,function (err,result) {
        if(err){
          // res.json({ success:false,code:0,message: err });
          console.log(err);
        }else{
          // console.log(result);
          //设置30天有效期
          let expires = moment().add(30, 'days').valueOf();
          let u = {
            userId:result._id,
            phone:result.phone
          }
          let token = jwt.encode({
            userId:doc._id,
            userInfo: JSON.stringify(u),
            exp: expires
          }, jwtSecret)

          res.json({ success:true,code:0,message: '欢迎使用小厨房服务！',token:token,userInfo:u })
        }
      })
    }
  })
})

router.post('/login',function (req,res) {
  let userInfo = {
    phone:req.body.phone,
    pwd:req.body.pwd,
  }
  if(!tools.check(0,userInfo.phone)){
    res.json({ success:false,code:4014,message: '请输入手机号' })
    return
  }
  if(!tools.check(0,userInfo.pwd)){
    res.json({ success:false,code:4024,message: '请输入密码' })
    return
  }
  Users.findOne({phone:userInfo.phone},function (err,doc) {
    if(err) {
      console.log(err);
      return next(err)
    }
    if(doc){
      userInfo.pwd = require('crypto').createHash('md5').update(userInfo.pwd + userInfo.phone).digest('base64');
      if(doc.pwd === userInfo.pwd){
        //设置30天有效期
        let expires = moment().add(30, 'days').valueOf();
        let u = {
          userId:doc._id,
          phone:doc.phone
        }
        let token = jwt.encode({
          uId:u._id,
          userInfo: JSON.stringify(u),
          exp: expires
        }, jwtSecret)

        res.json({ success:true,code:0,message: '欢迎使用小厨房服务!',token:token,userInfo:u})
      }else{
        res.json({ success:false,code:50012,message: '密码错误!' })
      }
    }else{
      res.json({ success:false,code:50013,message: '账号错误!' })
    }
  })
})

module.exports = router;
